package com.sunfield.windpower.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunfield.baseframe.base.BaseActivity;
import com.sunfield.baseframe.base.BaseFragment;
import com.sunfield.baseframe.http.HttpResult;
import com.sunfield.baseframe.util.JsonUtil;
import com.sunfield.baseframe.util.MLog;
import com.sunfield.windpower.MyApplication;
import com.sunfield.windpower.R;
import com.sunfield.windpower.eventbus.CreateCookie;
import com.sunfield.windpower.eventbus.ExitNotification;
import com.sunfield.windpower.fragment.ContactsFragment_;
import com.sunfield.windpower.fragment.GuideFragment_;
import com.sunfield.windpower.fragment.HodorFragment_;
import com.sunfield.windpower.fragment.MessageFragment_;
import com.sunfield.windpower.fragment.SkyDriveFragment_;
import com.sunfield.windpower.http.HttpClient;
import com.sunfield.windpower.util.Tools;
import com.sunfield.windpower.util.UserUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.ViewsById;
import org.androidannotations.annotations.res.StringArrayRes;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener {

    @ViewsById({R.id.tv_tab_0, R.id.tv_tab_1, R.id.tv_tab_2, R.id.tv_tab_3, R.id.tv_tab_4})
    List<TextView> textViewList;

    @ViewsById({R.id.tv_red_point_0, R.id.tv_red_point_1, R.id.tv_red_point_2, R.id.tv_red_point_3, R.id.tv_red_point_4})
    List<TextView> pointList;

    @ViewsById({R.id.iv_tab_0, R.id.iv_tab_1, R.id.iv_tab_2, R.id.iv_tab_3, R.id.iv_tab_4})
    List<ImageView> imageViewList;

    @ViewById
    WebView webView;

    int currentIndex = -1;
    List<BaseFragment> fragments;

    @StringArrayRes(R.array.main_title_text)
    String[] titles;

    CreateCookie.CookieCreatedListener listener;

    @Bean
    HttpClient http;

    @AfterViews
    void init(){
        fragments = new ArrayList<>();

        fragments.add(GuideFragment_.builder().build());
        fragments.add(HodorFragment_.builder().build());
        fragments.add(MessageFragment_.builder().build());
        fragments.add(SkyDriveFragment_.builder().build());
        fragments.add(ContactsFragment_.builder().build());

        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setOnMenuItemClickListener(this);

        back_button.setVisibility(View.GONE);

        select(1);

        Intent intent = getIntent();
        Uri uri = intent.getData();
        if(uri != null){
            MLog.d("uri", uri.toString());
            MLog.d("uri", "ticket = " + uri.getQueryParameter("ticket"));
        }

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                cookieCreatedSuccess(url);
            }
        });

//        createCookie(new HttpHeadProviderImpl().getHttpBaseUrl() + HttpClient.URL_GET_GUIDE_MENU);

        http.getUnreadMessageCount(UserUtil.getUserId());
    }

    @Click({R.id.ll_tab_0, R.id.ll_tab_1, R.id.ll_tab_2, R.id.ll_tab_3, R.id.ll_tab_4})
    void click(View v){
        switch (v.getId()){
            case R.id.ll_tab_0:
                select(0);
                break;
            case R.id.ll_tab_1:
                select(1);
                break;
            case R.id.ll_tab_2:
                select(2);
                pointList.get(2).setText("");
                http.readMessage(UserUtil.getUserId());
                break;
            case R.id.ll_tab_3:
                select(3);
                break;
            case R.id.ll_tab_4:
                select(4);
                break;
        }
    }

    @Override
    public void onHttpResult(HttpResult result) {
        super.onHttpResult(result);
        if (result.match(http, "getUnreadMessageCount")){
            if(result.isSuccess()){
                pointList.get(2).setText(JsonUtil.GetStringByLevel(result.getJson(), "data"));
            }
        }
    }

    private void select(int index){
//        Assertion a = new AssertionImpl("wangnan");
//        HttpSession session = req.getSession();
//        session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, a);
//        debug();
        if(fragments == null){
            return;
        }
        if(index < 0 || index >= fragments.size()){
            return;
        }
        if(currentIndex == index){
            return;
        }
        BaseFragment fragment = fragments.get(index);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if(!fragment.isAdded()){
            ft.add(R.id.container, fragment);
        }
        if(currentIndex >= 0){
            ft.hide(fragments.get(currentIndex));
        }
        ft.show(fragment);

        ft.commitAllowingStateLoss();
        currentIndex = index;

        for(int i=0;i<textViewList.size();i++){
            textViewList.get(i).setSelected(i == index);
            imageViewList.get(i).setSelected(i == index);
        }
        pointList.get(index).setText("0");

        setTitleText(titles[index]);
    }

    void debug(){
        if(MyApplication.DEBUG){
            WebViewActivity_.intent(this).start();
        }
    }

    @Override
    protected boolean isSlidingRightBack() {
        return false;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_enter:
                QuickEnterActivity_.intent(this).start();
                break;
        }
        return false;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.base_slide_down_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Intent intent = new Intent(Intent.ACTION_MAIN);
//        intent.addCategory(Intent.CATEGORY_HOME);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        this.startActivity(intent);
//        startActivity(intent);
//        System.exit(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHttpResult(ExitNotification notification) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void createCookie(CreateCookie createCookie){
        listener = createCookie.getListener();
        createCookie(createCookie.getUrl());
    }

    private void createCookie(String url){
        if(url != null){
            if(Tools.getCookie(url) == null){
                webView.loadUrl(url);
            }else{
                cookieCreatedSuccess(url);
            }
        }
    }

    private void cookieCreatedSuccess(String url) {
        if(listener != null){
            listener.cookieCreated(url);
            listener = null;
        }
    }
}
